package com.corn.kafka.consumer;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.*;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2022/7/1 15:47
 */

public class KafkaSeekOffsetConsumerDemo {

    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "node1:9092,node2:9092");
        // group.id
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "consumer.haha");
        properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);
        Collection<String> topics = new ArrayList<>();
        // 订阅的主题
        topics.add("test_topic");
        consumer.subscribe(topics);

        // 为了避免程序执行到这里kafka链接还没建立完成
        Set<TopicPartition> topicPartitions = new HashSet<>();
        while (topicPartitions.size() <= 0) {
            consumer.poll(Duration.ofSeconds(1));
            // 获取所有的topic和partition信息
            topicPartitions = consumer.assignment();
        }
        // 遍历所有分区，并指定 offset 从 5 的位置开始消费
        for (TopicPartition topicPartition : topicPartitions) {
            consumer.seek(topicPartition, 5);
        }

        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(2));
            for (ConsumerRecord<String, String> record : records) {
                System.out.println(record);
            }
        }

    }
}
